package shells

import (
	"github.com/sirupsen/logrus"
	"os"
	"os/exec"
	"os/signal"
)

type SignalsForwarder chan os.Signal

func (signalChannel *SignalsForwarder) Close() error {
	signal.Stop(*signalChannel)
	*signalChannel <- nil
	close(*signalChannel)
	return nil
}

func NewSignalsForwarder(signals []os.Signal, c *exec.Cmd, logger *logrus.Logger, cmdChannel chan error) SignalsForwarder {
	signalChannel := make(chan os.Signal, 1)
	signal.Notify(signalChannel, signals...)
	go func() {
		for {
			select {
			case s := <-signalChannel:
				logger.Debugf("Forward signal %v to terraform.", s)
				err := c.Process.Signal(s)
				if err != nil {
					logger.Errorf("Error forwarding signal: %v", err)
				}
			case <-cmdChannel:
				return
			}
		}
	}()
	return signalChannel
}
